package com.xuecheng.manage_media.service;

import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_media.dao.MediaFileRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Aniymx on 2019/1/8 18:08.
 */
@Service
public class MediaFileService {
    @Autowired
    private MediaFileRepository mediaFileRepository;

    public QueryResponseResult list(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        MediaFile mediaFile = new MediaFile();

        if (queryMediaFileRequest == null) {
            queryMediaFileRequest = new QueryMediaFileRequest();
        }
        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
        exampleMatcher.withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains())//tag字段模糊匹配
                .withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains())//文件原始名称模糊匹配
                .withMatcher("processStatus", ExampleMatcher.GenericPropertyMatchers.exact());//处理状态精确匹配（默认）
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getTag())) {
            mediaFile.setTag(queryMediaFileRequest.getTag());
        }

        if (StringUtils.isNotEmpty(queryMediaFileRequest.getFileOriginalName())) {
            mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
        }

        if (StringUtils.isNotEmpty(queryMediaFileRequest.getProcessStatus())) {
            mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
        }
        Example<MediaFile> mediaFileExample = Example.of(mediaFile, exampleMatcher);
        page = page - 1;
        Pageable pageable = new PageRequest(page, size);
        Page<MediaFile> mediaFilePage = mediaFileRepository.findAll(mediaFileExample, pageable);
        List<MediaFile> content = mediaFilePage.getContent();
        int totalPages = mediaFilePage.getTotalPages();
        QueryResult<MediaFile> objectQueryResult = new QueryResult<>();
        objectQueryResult.setList(content);
        objectQueryResult.setTotal(totalPages);
        QueryResponseResult queryResponseResult = new QueryResponseResult(CommonCode.SUCCESS, objectQueryResult);
        return queryResponseResult;

    }
}
